package com.example.music_mediaplayer.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.example.music_mediaplayer.R;

import com.example.music_mediaplayer.fragment.LocationFragment;
import com.example.music_mediaplayer.globalvariable.GlobalVariable;
import com.example.music_mediaplayer.model.SongsInfomation;
import com.example.music_mediaplayer.tool.DialogUtil;
import com.example.music_mediaplayer.tool.HanziToPinyin;
import com.example.music_mediaplayer.tool.LogoutT;
import com.example.music_mediaplayer.tool.ToastTools;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by quan on 2018/1/5.
 */
public class MyListViewAdapter extends BaseAdapter{
    private List<SongsInfomation> list;
    private Context context;
    private LayoutInflater inflater;
    private PopupWindow popupWindow;
    private WindowManager wm;
    private int flg;//用于判断是当前是哪个list


    public MyListViewAdapter(Context context , List<SongsInfomation> list ,int flg){
        this.context = context;
        this.list = list;
        this.flg = flg;
        inflater = LayoutInflater.from(context);
    }
    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(final int i, View view, final ViewGroup viewGroup) {
        final ViewHolder viewHolder;
        if (view == null){
            viewHolder = new ViewHolder();
            view = inflater.inflate(R.layout.list_item,null);
            viewHolder.te_song_name = (TextView) view.findViewById(R.id.song_name);
            viewHolder.te_song_name.setSelected(true);
            viewHolder.te_song_artist = (TextView) view.findViewById(R.id.song_artist);
            viewHolder.te_song_artist.setSelected(true);
            viewHolder.imageView = (ImageView) view.findViewById(R.id.img_more);
            viewHolder.progressBar = (ProgressBar) view.findViewById(R.id.pb_progress_bar);
            view.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.te_song_name.setText(list.get(i).getSongName());
        viewHolder.te_song_artist.setText(list.get(i).getSongArtist());
//        viewHolder.progressBar.setVisibility(View.GONE);
        viewHolder.imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                list.get(i).setFlg(true);
                viewGroup.setAlpha(0.2f);
                //获取屏幕高度和宽度
                wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//                int screenHeight = wm.getDefaultDisplay().getHeight();
                int screenWidth = wm.getDefaultDisplay().getWidth();
                View popupView = inflater.inflate(R.layout.popupwindow_item,null);
                RelativeLayout rela_download = (RelativeLayout) popupView.findViewById(R.id.popup_rela_1);
                RelativeLayout rela_scan = (RelativeLayout) popupView.findViewById(R.id.popup_rela_2);
//                RelativeLayout rela_progressbar = (RelativeLayout) popupView.findViewById(R.id.popup_rela_3);
//                final ProgressBar progressBar = (ProgressBar) popupView.findViewById(R.id.progress_bar);
                TextView te_song_name = (TextView) popupView.findViewById(R.id.popup_te_song_name);
                if (flg == 2){
                    rela_scan.setVisibility(View.GONE);
                    te_song_name.setText(list.get(i).getSongName());
                }else {
                    rela_download.setVisibility(View.GONE);
//                    rela_progressbar.setVisibility(View.VISIBLE);
//                    rela_song_name.setVisibility(View.GONE);
                    te_song_name.setText("选择");
                }

                rela_download.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                        viewGroup.setAlpha(1f);
                        OkHttpUtils
                                .get()
                                .url(list.get(i).getSongPath())
                                .build()
                                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getPath()+"/youlisten/music",list.get(i).getSongName()+" - "+list.get(i).getSongArtist()+".mp3") {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {
                                        Log.i("111111","onError:"+e.getMessage());
                                        ToastTools.toastMsg(context,e.getMessage());
                                    }

                                    @Override
                                    public void onResponse(File response, int id) {
                                        Log.i("111111",response.getAbsolutePath());
                                    }

                                    @Override
                                    public void onBefore(Request request, int id) {
                                        super.onBefore(request, id);
                                    }

                                    @Override
                                    public void inProgress(float progress, long total, int id) {
                                        Log.i("111111","inProgress:"+(int)(100*progress));
                                        Handler handler = new Handler(){
                                            @Override
                                            public void handleMessage(Message msg) {
                                                super.handleMessage(msg);
                                                switch (msg.what){
                                                    case 1:
                                                        if (list.get(i).getFlg()==true){
                                                            viewHolder.progressBar.setVisibility(View.VISIBLE);
                                                            for (int j = 1 ; j<=msg.arg1;j++){
                                                                viewHolder.progressBar.setProgress(j);
                                                                if (j==100){
                                                                    viewHolder.progressBar.setVisibility(View.GONE);
                                                                    list.get(i).setFlg(false);
                                                                    ToastTools.toastMsg(context,"下载成功!");
                                                                }
                                                            }
                                                        }
//                                                        ContentValues newValue = new ContentValues();
//                                                        newValue.put(MediaStore.Audio.Media.TITLE,list.get(i).getSongName());
//                                                        newValue.put(MediaStore.Audio.Media.ARTIST,list.get(i).getSongArtist());
//                                                        newValue.put(MediaStore.Audio.Media.DATA,Environment.getExternalStorageDirectory().getPath()+"/music/"+list.get(i).getSongName()+" - "+list.get(i).getSongArtist()+".mp3");
//                                                        ContentResolver resolver = context.getContentResolver();
//                                                        int a = resolver.update(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI,newValue,null,null);
//                                                        LogoutT.logout(a+"    llll ");
//                                                        LogoutT.logout(Environment.getExternalStorageDirectory().getPath()+"/music/"+list.get(i).getSongName()+" - "+list.get(i).getSongArtist()+".mp3"+"    llll ");
                                                        break;
                                                }
                                            }
                                        };
                                        Message msg = new Message();
                                        msg.what = 1;
                                        msg.arg1 = (int)(100*progress);
                                        handler.sendMessage(msg);
                                    }
                                });
                    }
                });
                rela_scan.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                        viewGroup.setAlpha(1f);
                        DialogUtil.show(context, R.string.scan);
                        GlobalVariable.LocationSongList.clear();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                DialogUtil.dismiss2Msg("扫描完成");
                                getLocationSongList();
                                sortSongList();
                                LocationFragment.adapter.notifyDataSetChanged();
                            }
                        },2500);
                    }
                });
                popupWindow = new PopupWindow(popupView, screenWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
                //设置动画
                popupWindow.setAnimationStyle(R.style.popup_window_anim);
                //设置背景颜色
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
                //设置可以获取焦点
                popupWindow.setFocusable(true);
                //设置可以触摸弹出框以外的区域
                popupWindow.setOutsideTouchable(true);
                //更新popupwindow的状态
                popupWindow.update();
                //从底部弹出
                popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        viewGroup.setAlpha(1f);
                    }
                });
//                ToastTools.toastMsg(context,"被点击了");
            }
        });
        return view;
    }


    /**
     * 获取本地音乐列表
     */
    public void getLocationSongList(){
        /**
         * 查询媒体数据库
         * 参数分别为（路径，要查询的列名，条件语句，条件参数，排序）
         */
        LogoutT.logout("333333333");
        Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null,MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
        //遍历媒体数据库
        if (cursor.moveToFirst()){
            while (!cursor.isAfterLast()){
                //歌曲编号
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
//                LogoutT.logout(id+"   id");
                //歌曲标题
                String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                LogoutT.logout(title+"   title");
                //歌曲的歌手名
                String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                LogoutT.logout(artist+"   artist");
                //歌曲文件路径
                String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                LogoutT.logout(url+"   url");
                //歌曲的总播放时长
                int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
//                LogoutT.logout(duration+"   duration");
                //歌曲文件的大小
                Long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));

                if (size > 1024 * 800){//大于800K
                    SongsInfomation songsInfomation = new SongsInfomation();
                    songsInfomation.setSongArtist(artist);
                    songsInfomation.setSongName(title);
                    songsInfomation.setSongPath(url);
                    songsInfomation.setDuration(duration);
                    GlobalVariable.LocationSongList.add(songsInfomation);
                }
                cursor.moveToNext();
            }
        }
        getSongOnFile();
    }

    public void sortSongList(){
        if (GlobalVariable.LocationSongList.size()!=0){
            for (SongsInfomation s : GlobalVariable.LocationSongList){
                s.setInitial(getLetter(s.getSongName()));
            }
        }
        sort();
    }


    /**
     * 排序方法
     */
    public void sort(){
        Collections.sort(GlobalVariable.LocationSongList, new Comparator<SongsInfomation>() {
            @Override
            public int compare(SongsInfomation o1, SongsInfomation o2) {
                if (o1.getInitial().equals(o2.getInitial())){
                    return o1.getSongName().compareTo(o2.getSongName());
                }else{
                    if ("#".equals(o1.getInitial())){
                        return 1;
                    }else if ("#".equals(o2.getInitial())){
                        return -1;
                    }
                    return o1.getInitial().compareTo(o2.getInitial());
                }
            }
        });
    }


    /**
     * 根据字符串获取当前首字母
     * @param name
     * @return
     */
    public String getLetter(String name){
        String DefaultLetter = "#";
        if (TextUtils.isEmpty(name)){
            return DefaultLetter;
        }
        char initial = name.toLowerCase().charAt(0);
        if (Character.isDigit(initial)){
            return DefaultLetter;
        }
        ArrayList<HanziToPinyin.Token> l = HanziToPinyin.getInstance().get(name.substring(0,1));
        if (l != null && l.size()>0 && l.get(0).target.length()>0){
            HanziToPinyin.Token token = l.get(0);
            //toLowerCase返回小写，toUpperCase()返回大写
            String letter = token.target.substring(0,1).toLowerCase();
            char c = letter.charAt(0);
            //这里的'a'和'z'要和letter的大小写保持一直。
            if (c<'a'||c>'z'){
                return DefaultLetter;
            }
            return letter;
        }
        return DefaultLetter;
    }

    /**
     * 从指定文件夹中获取音乐资源
     */
    public void getSongOnFile(){
        //音乐列表
        //得到song文件夹的路径，File.separator(/)
        String filePath = Environment.getExternalStorageDirectory().getPath()+File.separator + "youlisten/music";
        //得到该路径文件夹下所有的文件
        File fileAll = new File(filePath);
        File[] files = fileAll.listFiles();
        //将所有的文件存入GlobalVariable.LocationSongList中，并过滤所有图片格式的文件
        for(int i = 0;i<files.length;i++){
            File file = files[i];
            if (checkIsSongFile(file.getPath())){
                String[] fs = file.getPath().split("/");
                String[] ns = fs[6].split(" - ");
                Log.i("003003",ns[0]);
                Log.i("004004",ns[1]);
                SongsInfomation songsInfomation = new SongsInfomation();
                songsInfomation.setSongPath(file.getPath());
                songsInfomation.setSongName(ns[0]);
                songsInfomation.setSongArtist(ns[1].substring(0 , ns[1].indexOf(".")));
                GlobalVariable.LocationSongList.add(songsInfomation);
                LogoutT.logout(GlobalVariable.LocationSongList.get(0).getSongPath()+"  aaa aa ");
            }
        }
    }

    /**
     * 检查扩展名，得到图片格式的文件
     * @param fName
     * @return
     */
    @SuppressLint("DefaultLocale")
    public boolean checkIsSongFile(String fName){
        boolean isSongFile = false;
        //获取扩展名
        String fileEnd = fName.substring(fName.lastIndexOf(".")+1,fName.length()).toLowerCase();
        if (fileEnd.equals("mp3")||fileEnd.equals("wav")||fileEnd.equals("mid")||fileEnd.equals("asf")||fileEnd.equals("mpg")||fileEnd.equals("avi")||fileEnd.equals("tti")){
            isSongFile = true;
        }else {
            isSongFile = false;
        }
        return isSongFile;
    }


    public class ViewHolder{
        public TextView te_song_name;
        public TextView te_song_artist;
        public ImageView imageView;
        public ProgressBar progressBar;
    }
}
